package ncut.shumei.service.impl;

import ncut.shumei.dao.ElevatorDao;
import ncut.shumei.dto.ElevatorCreateRequest;
import ncut.shumei.dto.ElevatorDTO;
import ncut.shumei.entity.Elevator;
import ncut.shumei.exception.BusinessException;
import ncut.shumei.service.ElevatorService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ElevatorServiceImpl implements ElevatorService {

    @Autowired
    private ElevatorDao elevatorDao;

    @Override
    public List<ElevatorDTO> getElevators(String building, String status) {
        return elevatorDao.findAll(building, status).stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    @Override
    public ElevatorDTO getElevator(Integer id) {
        Elevator elevator = elevatorDao.findById(id);
        if (elevator == null) {
            throw new BusinessException("电梯不存在");
        }
        return convertToDTO(elevator);
    }

    @Override
    @Transactional
    public ElevatorDTO createElevator(ElevatorCreateRequest request) {
        Elevator elevator = new Elevator();
        BeanUtils.copyProperties(request, elevator);
        
        // 设置维护日期
        LocalDate now = LocalDate.now();
        elevator.setLastMaintenanceDate(now);
        elevator.setNextMaintenanceDate(now.plusDays(request.getMaintenanceInterval()));
        
        elevatorDao.insert(elevator);
        return convertToDTO(elevator);
    }

    @Override
    @Transactional
    public ElevatorDTO updateElevator(Integer id, ElevatorCreateRequest request) {
        Elevator elevator = elevatorDao.findById(id);
        if (elevator == null) {
            throw new BusinessException("电梯不存在");
        }
        
        BeanUtils.copyProperties(request, elevator);
        elevatorDao.update(elevator);
        return convertToDTO(elevator);
    }

    @Override
    @Transactional
    public void deleteElevator(Integer id) {
        Elevator elevator = elevatorDao.findById(id);
        if (elevator == null) {
            throw new BusinessException("电梯不存在");
        }
        elevatorDao.deleteById(id);
    }

    @Override
    @Transactional
    public void updateElevatorStatus(Integer id, String status) {
        Elevator elevator = elevatorDao.findById(id);
        if (elevator == null) {
            throw new BusinessException("电梯不存在");
        }
        elevatorDao.updateStatus(id, status);
    }

    private ElevatorDTO convertToDTO(Elevator elevator) {
        ElevatorDTO dto = new ElevatorDTO();
        BeanUtils.copyProperties(elevator, dto);
        return dto;
    }
} 